package com.mbl.base.modular.mall.mbl_service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.mbl.base.config.enums.ResultEnum;
import com.mbl.base.config.security.SecurityUser;
import com.mbl.base.core.common.constant.MblConstantFactory;
import com.mbl.base.core.common.dto.MblResult;
import com.mbl.base.core.common.exception.BaseException;
import com.mbl.base.core.common.page.LayuiPageFactory;
import com.mbl.base.core.modular.express.ExpressService;
import com.mbl.base.core.modular.express.dao.ExpressInfo;
import com.mbl.base.core.modular.task.TaskService;
import com.mbl.base.core.modular.task.UtilTask;
import com.mbl.base.core.utils.UtilRandom;
import com.mbl.base.core.utils.UtilSecurity;
import com.mbl.base.modular.mall.constant.CouponUserConstant;
import com.mbl.base.modular.mall.constant.GrouponConstant;
import com.mbl.base.modular.mall.constant.OrderHandleOption;
import com.mbl.base.modular.mall.entity.*;
import com.mbl.base.modular.mall.service.*;
import com.mbl.base.modular.mall.task.OrderUnpaidTask;
import com.mbl.base.modular.mall.utils.OrderUtil;
import com.mbl.base.modular.member.entity.User;
import com.mbl.base.modular.member.service.IUserService;
import org.apache.commons.io.IOUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UtilOrderService {
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IGrouponService grouponService;
    @Autowired
    private IGrouponRulesService grouponRulesService;
    @Autowired
    private ICouponService couponService;
    @Autowired
    private ICouponUserService couponUserService;
    @Autowired
    private IOrderGoodsService orderGoodsService;
    @Autowired
    private IGoodsProductService goodsProductService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ExpressService expressService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IUserService userService;



    /**
     * 发货
     * 1. 检测当前订单是否能够发货
     * 2. 设置订单发货状态
     * @return 订单操作结果
     * 成功则 { errno: 0, errmsg: '成功' }
     * 失败则 { errno: XXX, errmsg: XXX }
     */
    public void ship(Integer orderId, String shipSn, String shipChannel) {
        if (orderId == null || shipSn == null || shipChannel == null) {
            throw new BaseException("订单异常，请联系管理员！");
        }
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new BaseException("订单异常，请联系管理员！");
        }
        // 如果订单不是已付款状态，则不能发货
        if (!order.getOrderStatus().equals(Integer.valueOf(OrderUtil.STATUS_PAY))) {
            throw new BaseException("订单不能确认收货！");
        }
        order.setOrderStatus(Integer.valueOf(OrderUtil.STATUS_SHIP));
        order.setShipSn(shipSn);
        order.setShipChannel(shipChannel);
        order.setShipTime(LocalDateTime.now());
    }
    /**
     * 订单列表
     * @param userId   用户ID
     * @param showType 订单信息：
     *                 0，全部订单；
     *                 1，待付款；
     *                 2，待发货；
     *                 3，待收货；
     *                 4，待评价。
     * @return 订单列表
     */
    public Object list(Long userId, Integer showType) {
        if (userId == null) {
            return MblResult.renum(ResultEnum.PARAME_ERR);
        }
        List<Short> orderStatus = OrderUtil.orderStatus(showType);
        final IPage<Order> orderIPage = orderService.queryByOrderStatus(userId, orderStatus);
        List<Map<String, Object>> orderVoList = new ArrayList<>(orderIPage.getRecords().size());
        for (Order o : orderIPage.getRecords()) {
            Map<String, Object> orderVo = new HashMap<>();
            orderVo.put("id", o.getId());
            orderVo.put("orderSn", o.getOrderSn());
            orderVo.put("actualPrice", o.getActualPrice());
            orderVo.put("orderStatusText", OrderUtil.orderStatusText(o));
            orderVo.put("handleOption", OrderUtil.build(o));

            orderVo.put("isGroupin", false);
            List<OrderGoods> orderGoodsList = orderGoodsService.queryByOrderid(o.getId());
            List<Map<String, Object>> orderGoodsVoList = new ArrayList<>(orderGoodsList.size());
            for (OrderGoods orderGoods : orderGoodsList) {
                Map<String, Object> orderGoodsVo = new HashMap<>();
                orderGoodsVo.put("id", orderGoods.getId());
                orderGoodsVo.put("goodsName", orderGoods.getGoodsName());
                orderGoodsVo.put("number", orderGoods.getNumber());
                orderGoodsVo.put("picUrl", orderGoods.getPicUrl());
                orderGoodsVo.put("specifications", orderGoods.getSpecifications());
                orderGoodsVo.put("price",orderGoods.getPrice());
                orderGoodsVoList.add(orderGoodsVo);
            }
            orderVo.put("goodsList", orderGoodsVoList);

            orderVoList.add(orderVo);
        }
        final HashMap<String, Object> map = new HashMap<>();
        map.put("list", orderVoList);
        map.put("total", orderIPage.getTotal());
        return MblResult.success(map);
    }
    /**
     * 订单详情
     *
     * @param userId  用户ID
     * @param orderId 订单ID
     * @return 订单详情
     */
    public Object detail(Long userId, Long orderId) {
        if (userId == null) {
            return MblResult.renum(ResultEnum.PARAME_ERR);
        }
        // 订单信息
        Order order = orderService.getById(orderId);
        if (null == order) {
            throw new BaseException(500, "订单不存在");
        }
        if (!order.getUserId().equals(userId)) {
            throw new BaseException(500, "不是当前用户的订单");
        }
        Map<String, Object> orderVo = new HashMap<String, Object>();
        orderVo.put("id", order.getId());
        orderVo.put("orderSn", order.getOrderSn());
        orderVo.put("message", order.getMessage());
        orderVo.put("addTime", order.getCreateTime());
        orderVo.put("consignee", order.getConsignee());
        orderVo.put("mobile", order.getMobile());
        orderVo.put("address", order.getAddress());
        orderVo.put("goodsPrice", order.getGoodsPrice());
        orderVo.put("couponPrice", order.getCouponPrice());
        orderVo.put("freightPrice", order.getFreightPrice());
        orderVo.put("actualPrice", order.getActualPrice());
        orderVo.put("orderStatusText", OrderUtil.orderStatusText(order));
        orderVo.put("handleOption", OrderUtil.build(order));
        orderVo.put("expCode", order.getShipChannel());
        orderVo.put("expName", expressService.getVendorName(order.getShipChannel()));
        orderVo.put("expNo", order.getShipSn());

        List<OrderGoods> orderGoodsList = orderGoodsService.queryByOrderid(order.getId());

        Map<String, Object> result = new HashMap<>();
        result.put("orderInfo", orderVo);
        result.put("orderGoods", orderGoodsList);
        // 订单状态为已发货且物流信息不为空
        //"YTO", "800669400640887922"
        if (order.getOrderStatus().equals(OrderUtil.STATUS_SHIP)) {
            ExpressInfo ei = expressService.getExpressInfo(order.getShipChannel(), order.getShipSn());
            if(ei == null){
                result.put("expressInfo", new ArrayList<>());
            }
            else {
                result.put("expressInfo", ei);
            }
        }
        else{
            result.put("expressInfo", new ArrayList<>());
        }
        return MblResult.success(result);

    }
    /**
     * 提交订单
     * <p>
     * 1. 创建订单表项和订单商品表项;
     * 2. 购物车清空;
     * 3. 优惠券设置已用;
     * 4. 商品货品库存减少;
     * 5. 如果是团购商品，则创建团购活动表项。（团购商品只能单独团购）(开团传入团购规则id，入团传入grouponLinkId)
     *
     * @param userId 用户ID
     * @return 提交订单操作结果
     */
    @Transactional
    public Object submit(Long userId, Long cartId, Long addressId, Long couponId, Long userCouponId, Long grouponRulesId, Long grouponLinkId,String message) {
        if (userId == null || cartId == null || addressId == null || couponId == null || userCouponId == null) {
            return MblResult.renum(ResultEnum.PARAME_ERR);
        }
        // 团购规则验证并返回团购优惠金额
        final BigDecimal grouponPrice = grouponVerification(userId, grouponLinkId, grouponRulesId);

        // 收货地址
        Address checkedAddress = addressService.getById(addressId);
        if (checkedAddress == null) {
            return MblResult.renum(ResultEnum.PARAME_ERR);
        }
        // 货品列表
        List<Cart> checkedGoodsList = getGoodsProductList(cartId, userId);
        // 商品总价格 Todo 这里存在bug如果购物车存在多个团购的商品怎么处理
        BigDecimal checkedGoodsPrice = new BigDecimal(0);
        GrouponRules grouponRules = null;
        if(grouponPrice.compareTo(new BigDecimal("0")) > 0) {
            grouponRules = grouponRulesService.getById(grouponService.getById(grouponLinkId).getRulesId());
        }
        for (Cart checkGoods : checkedGoodsList) {
            checkedGoodsPrice = checkedGoodsPrice.add(checkGoods.getPrice().multiply(new BigDecimal(checkGoods.getNumber())));
            //  只有当团购规格商品ID符合才进行团购优惠
            if(grouponPrice.compareTo(new BigDecimal("0")) > 0 && grouponRules != null && grouponRules.getGoodsId().equals(checkGoods.getGoodsId())){
                checkedGoodsPrice = checkedGoodsPrice.subtract(grouponPrice);
            }
        }
        // 获取可用的优惠券信息,使用优惠券减免的金额
        BigDecimal couponPrice = new BigDecimal(0);
        // 如果couponId=0则没有优惠券，couponId=-1则不使用优惠券
        if (couponId != 0 && couponId != -1) {
            Coupon coupon = couponService.checkCoupon(userId, couponId, userCouponId, checkedGoodsPrice);
            if (coupon == null) {
                return MblResult.renum(ResultEnum.PARAME_ERR);
            }
            couponPrice = coupon.getDiscount();
        }

        // 根据订单商品总价计算运费，满足条件（例如88元）则免运费，否则需要支付运费（例如8元）；
        BigDecimal freightPrice = new BigDecimal(0);
        if (checkedGoodsPrice.compareTo(new BigDecimal(MblConstantFactory.me().getDictValByCode("minFreightConfig"))) < 0) {
            freightPrice = new BigDecimal(MblConstantFactory.me().getDictValByCode("freightPrice"));
        }
        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0);
        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0));
        // 最终支付费用
        BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);
        Long orderId = null;
        Order order = null;
        // 订单
        order = new Order();
        order.setUserId(userId);
        order.setOrderSn(generateOrderSn());
        order.setOrderStatus(Integer.valueOf(OrderUtil.STATUS_CREATE));
        order.setConsignee(checkedAddress.getName());
        order.setMobile(checkedAddress.getTel());
        order.setMessage(message);
        String detailedAddress = checkedAddress.getProvince() + checkedAddress.getCity() + checkedAddress.getCounty() + " " + checkedAddress.getAddressDetail();
        order.setAddress(detailedAddress);
        order.setGoodsPrice(checkedGoodsPrice);
        order.setFreightPrice(freightPrice);
        order.setCouponPrice(couponPrice);
        order.setIntegralPrice(integralPrice);
        order.setOrderPrice(orderTotalPrice);
        order.setActualPrice(actualPrice);
        // 有团购
        if (grouponRules != null) {
            order.setGrouponPrice(grouponPrice);    //  团购价格
        } else {
            order.setGrouponPrice(new BigDecimal(0));    //  团购价格
        }
        // 添加订单表项
        orderService.save(order);
        orderId = order.getId();
        // 添加订单商品表项
        for (Cart cartGoods : checkedGoodsList) {
            // 订单商品
            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderId(order.getId());
            orderGoods.setGoodsId(cartGoods.getGoodsId());
            orderGoods.setGoodsSn(cartGoods.getGoodsSn());
            orderGoods.setProductId(cartGoods.getProductId());
            orderGoods.setGoodsName(cartGoods.getGoodsName());
            orderGoods.setPicUrl(cartGoods.getPicUrl());
            orderGoods.setPrice(cartGoods.getPrice());
            orderGoods.setNumber(cartGoods.getNumber());
            orderGoods.setSpecifications(cartGoods.getSpecifications());
            orderGoodsService.save(orderGoods);
        }

        // 删除购物车里面的商品信息
        cartService.clearGoods(userId);
        // 商品货品数量减少
        for (Cart checkGoods : checkedGoodsList) {
            Long productId = checkGoods.getProductId();
            GoodsProduct product = goodsProductService.getById(productId);
            int remainNumber = product.getNumber() - checkGoods.getNumber();
            if (remainNumber < 0) {
                throw new RuntimeException("下单的商品货品数量大于库存量");
            }
            if (goodsProductService.reduceStock(productId, checkGoods.getNumber()) == 0) {
                throw new RuntimeException("商品货品库存减少失败");
            }
        }
        // 如果使用了优惠券，设置优惠券使用状态
        if (couponId != 0 && couponId != -1) {
            CouponUser couponUser = couponUserService.getById(userCouponId);
            couponUser.setStatus(Integer.valueOf(CouponUserConstant.STATUS_USED));
            couponUser.setUsedTime(LocalDateTime.now());
            couponUser.setOrderId(orderId);
            couponUserService.updateById(couponUser);
        }
        //如果是团购项目，添加团购信息
        if (grouponRules != null) {
            Groupon groupon = new Groupon();
            groupon.setOrderId(orderId);
            groupon.setStatus(Integer.valueOf(GrouponConstant.STATUS_NONE));
            groupon.setUserId(userId);
            groupon.setRulesId(grouponRules.getId());
            //参与者
            if (grouponLinkId != null && grouponLinkId > 0) {
                //参与的团购记录
                Groupon baseGroupon = grouponService.getById(grouponLinkId);
                groupon.setCreatorUserId(baseGroupon.getCreatorUserId());
                groupon.setGrouponId(grouponLinkId);
                groupon.setShareUrl(baseGroupon.getShareUrl());
                grouponService.save(groupon);
            } else {
                groupon.setCreatorUserId(userId);
                groupon.setCreatorUserTime(LocalDateTime.now());
                groupon.setGrouponId(0l);
                grouponService.save(groupon);
                grouponLinkId = groupon.getId();
            }
        }

        // 订单支付超期任务
        UtilTask.addTask(new OrderUnpaidTask(orderId));
        Map<String, Object> data = new HashMap<>();
        data.put("orderId", orderId);
        if (grouponRules != null) {
            data.put("grouponLinkId", grouponLinkId);
        }
        else {
            data.put("grouponLinkId", 0);
        }
        return MblResult.success();
    }


    /**
     * 获取选中的商品列表
     * @param cartId
     * @param userId
     * @return
     */
    private List<Cart> getGoodsProductList(Long cartId, Long userId){
        List<Cart> checkedGoodsList = null;
        if (cartId.equals(0l)) {
            checkedGoodsList = cartService.getByUidAndChecked(userId);
        } else {
            Cart cart = cartService.getById(cartId);
            checkedGoodsList = new ArrayList<>(1);
            checkedGoodsList.add(cart);
        }
        if (checkedGoodsList.size() == 0) {
            throw new BaseException(ResultEnum.PARAME_ERR.getValue(), ResultEnum.PARAME_ERR.getStr());
        }
        return checkedGoodsList;
    }


    /**
     * 微信付款成功或失败回调接口
     * <p>
     * 1. 检测当前订单是否是付款状态;
     * 2. 设置订单付款成功状态相关信息;
     * 3. 响应微信商户平台.
     * @param request  请求内容
     * @param response 响应内容
     * @return 操作结果
     */
    @Transactional
    public Object payNotify(HttpServletRequest request, HttpServletResponse response) {
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }
        WxPayOrderNotifyResult result = null;
        try {
            result = wxPayService.parseOrderNotifyResult(xmlResult);
            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode()) || !WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())){
                throw new WxPayException("微信通知支付失败！");
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }
        String orderSn = result.getOutTradeNo();
        String payId = result.getTransactionId();
        // 分转化成元
        String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
        orderHandleSuccess(orderSn, payId, totalFee);
        return WxPayNotifyResponse.success("处理成功!");
    }

    public void orderHandleSuccess(String orderSn, String payId, String totalFee){
        Order order = orderService.findBySn(orderSn);
        if (order == null) {
            throw new BaseException("订单不存在：" + orderSn);
        }
        // 检查这个订单是否已经处理过
        if (OrderUtil.hasPayed(order)) {
            throw new BaseException("订单已经处理成功!");
        }
        // 检查支付订单金额
        if (!totalFee.equals(order.getActualPrice().toString())) {
            throw new BaseException("支付金额异常!");
        }
        order.setPayId(payId);
        order.setPayTime(LocalDateTime.now());
        order.setOrderStatus(Integer.valueOf(OrderUtil.STATUS_PAY));
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            // 这里可能存在这样一个问题，用户支付和系统自动取消订单发生在同时
            // 如果数据库首先因为系统自动取消订单而更新了订单状态；
            // 此时用户支付完成回调这里也要更新数据库，而由于乐观锁机制这里的更新会失败
            // 因此，这里会重新读取数据库检查状态是否是订单自动取消，如果是则更新成支付状态。
            order = orderService.findBySn(orderSn);
            if (OrderUtil.isAutoCancelStatus(order)) {
                order.setPayId(payId);
                order.setPayTime(LocalDateTime.now());
                order.setOrderStatus(Integer.valueOf(OrderUtil.STATUS_PAY));
                orderService.updateWithOptimisticLocker(order);
            }
        }
        // 取消订单超时未支付任务
        taskService.removeTask(new OrderUnpaidTask(order.getId()));
        /**
         * 会员增加积分
         */
        final SecurityUser user = UtilSecurity.getUser();
        final User byId = userService.getById(user.getId());
        byId.setIntegral(byId.getIntegral() + Double.valueOf(totalFee).intValue());
        byId.updateById();
    }
    /**
     * 获取某个用户
     * 团购规则验证并返回团购优惠价格，无优惠则返回0
     * @param userId
     * @param goodsId
     * @return
     * Todo 需增加限制，一个商品只能有一个团购活动规则
     */
    private BigDecimal grouponVerificationGoods(Long userId, Long goodsId) {
        // 团购优惠金额
        BigDecimal grouponPrice = new BigDecimal(0);
        GrouponRules grouponRules = grouponRulesService.query().eq("goods_id", goodsId).one();
        if(grouponRules == null){
            return grouponPrice;
        }
        Groupon groupon = grouponService.query().eq("rules_id", grouponRules.getId()).eq("user_id", userId).one();
        if(groupon == null){
            return grouponPrice;
        }
        //团购规则已经过期
        if (grouponRules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_EXPIRE)) {
            throw new BaseException(500, "团购已过期!");
        }
        //团购规则已经下线
        if (grouponRules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_ADMIN)) {
            throw new BaseException(500, "团购已下线!");
        }
        //团购人数已满
        if(grouponService.countGroupon(groupon.getId()) >= (grouponRules.getDiscountMember() - 1)){
            throw new BaseException(500, "团购活动人数已满!");
        }
        // NOTE
        // 这里业务方面允许用户多次开团，以及多次参团，
        // 但是会限制以下两点：
        // （1）不允许参加已经加入的团购
        if(grouponService.hasJoin(userId, groupon.getId())){
            throw new BaseException(500, "团购活动已经参加!");
        }
        // （2）不允许参加自己开团的团购
        if(groupon.getCreatorUserId().equals(userId)){
            throw new BaseException(500, "团购活动已经参加!");
        }
        grouponPrice = grouponRules.getDiscount();
        return grouponPrice;
    }
    /**
     * 团购规则验证并返回团购优惠价格，无优惠则返回0
     *
     * @param userId
     * @param grouponLinkId
     * @param grouponRulesId
     * @return
     */
    private BigDecimal grouponVerification(Long userId, Long grouponLinkId, Long grouponRulesId) {
        // 团购优惠金额
        BigDecimal grouponPrice = new BigDecimal(0);
        //如果是团购项目,验证活动是否有效
        if (grouponRulesId != null && grouponRulesId > 0) {
            GrouponRules rules = grouponRulesService.getById(grouponRulesId);
            //找不到记录
            if (rules == null) {
                throw new BaseException(ResultEnum.PARAME_ERR.getValue(), ResultEnum.PARAME_ERR.getStr());
            }
            //团购规则已经过期
            if (rules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_EXPIRE)) {
                throw new BaseException(500, "团购已过期!");
            }
            //团购规则已经下线
            if (rules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_ADMIN)) {
                throw new BaseException(500, "团购已下线!");
            }
            if (grouponLinkId != null && grouponLinkId > 0) {
                //团购人数已满
                if(grouponService.countGroupon(grouponLinkId) >= (rules.getDiscountMember() - 1)){
                    throw new BaseException(500, "团购活动人数已满!");
                }
                // NOTE
                // 这里业务方面允许用户多次开团，以及多次参团，
                // 但是会限制以下两点：
                // （1）不允许参加已经加入的团购
                if(grouponService.hasJoin(userId, grouponLinkId)){
                    throw new BaseException(500, "团购活动已经参加!");
                }
                // （2）不允许参加自己开团的团购
                Groupon groupon = grouponService.getById(grouponLinkId);
                if(groupon.getCreatorUserId().equals(userId)){
                    throw new BaseException(500, "团购活动已经参加!");
                }
                grouponPrice = rules.getDiscount();
            }
        }
        return grouponPrice;
    }

    /**
     * 取消订单
     * <p>
     * 1. 检测当前订单是否能够取消；
     * 2. 设置订单取消状态；
     * 3. 商品货品库存恢复；
     * 4. TODO 优惠券；
     * @return 取消订单操作结果
     */
    @Transactional
    public Object cancel(Long orderId) {
        Order order = orderService.getById(orderId);
        // 检测是否能够取消
        OrderHandleOption handleOption = OrderUtil.build(order);
        if (!handleOption.isCancel()) {
            throw new BaseException("订单不能取消");
        }
        // 设置订单已取消状态
        order.setOrderStatus(Integer.valueOf(OrderUtil.STATUS_CANCEL));
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }
        // 商品货品数量增加
        List<OrderGoods> orderGoodsList = orderGoodsService.queryByOrderid(orderId);
        for (OrderGoods orderGoods : orderGoodsList) {
            Long productId = orderGoods.getProductId();
            Integer number = orderGoods.getNumber();
            if (goodsProductService.addStock(productId, number) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }
        return MblResult.success();
    }


    // TODO 这里应该产生一个唯一的订单，但是实际上这里仍然存在两个订单相同的可能性
    private String generateOrderSn() {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
        String now = df.format(LocalDate.now());
        String orderSn = now + UtilRandom.getRandomNum(6);
        while (orderService.query().eq("order_sn", orderSn).one() != null) {
            orderSn = now + UtilRandom.getRandomNum(6);
        }
        return orderSn;
    }
}
